package com.imooc.ad.controller;

import com.alibaba.fastjson.JSON;
import com.imooc.ad.annotation.IgnoreResponseAdvice;
import com.imooc.ad.client.SponsorClient;
import com.imooc.ad.client.vo.AdPlan;
import com.imooc.ad.client.vo.AdPlanGetRequest;
import com.imooc.ad.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 调用检索系统的时候，通过调用投放系统访问广告计划
 */
@Slf4j
@RestController
public class SearchController {

    private final RestTemplate restTemplate;
    private final SponsorClient sponsorClient;

    @Autowired
    public SearchController(RestTemplate restTemplate,SponsorClient sponsorClient){
        this.restTemplate = restTemplate;
        this.sponsorClient = sponsorClient;
    }

    /**
     * 使用Feign调用微服务获取AdPlan
     */
    @IgnoreResponseAdvice//不使用统一响应的返回结果
    @PostMapping("/getAdPlans")
    public CommonResponse<List<AdPlan>> getAdPlans(@RequestBody AdPlanGetRequest request){

        log.info("ad-search: getAdPlansByFeign -> {}", JSON.toJSONString(request));

        return sponsorClient.getAdPlans(request);
    }

    /**
     * 使用Ribbon调用微服务获取AdPlan
     */
    @SuppressWarnings("all")//忽略警告
    @IgnoreResponseAdvice//不使用统一响应的返回结果
    @PostMapping("/getAdPlansByRibbon")
    public CommonResponse<List<AdPlan>> getAdPlansByRibbon(@RequestBody AdPlanGetRequest request){

        log.info("ad-search: getAdPlansByRibbon -> {}", JSON.toJSONString(request));

        return restTemplate.postForEntity(
                "http://eureka-client-ad-sponsor/ad-sponsor/get/adPlan",request,CommonResponse.class
        ).getBody();
    }
}
